/******************************************************************************
* Copyright (C) 2020 ShenZhen Powerdata Information Technology Co.,Ltd
* All Rights Reserved.
* 本软件为***研制。未经本公司正式书面同意，其他任何个人、团体不得使用、
* 复制、修改或发布本软件.
*****************************************************************************/

package com.xxl.job.listener.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.alibaba.fastjson.JSON;
import com.xgf.common.xgfcommon.utils.StringUtils;
import com.xxl.job.listener.config.RocketMqConfig;
import com.xxl.job.listener.service.MailService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Title:
 * @ClassName: MailServiceImpl
 * @Description:TODO
 * @author: xgf
 * @date: 2020年2月23日 下午3:09:22
 * @since JDK1.8
 * @history 2020年2月23日 TODO 新建
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {
	
	private static final String mailBodyTemplate = "<h5>" + "1" + "：</span>" +
			"<table border=\"1\" cellpadding=\"3\" style=\"border-collapse:collapse; width:80%;\" >\n" +
			"   <thead style=\"font-weight: bold;color: #ffffff;background-color: #ff8c00;\" >" +
			"      <tr>\n" +
			"         <td width=\"20%\" >"+ "2" +"</td>\n" +
			"         <td width=\"10%\" >"+ "1" +"</td>\n" +
			"         <td width=\"20%\" >"+ "1" +"</td>\n" +
			"         <td width=\"10%\" >"+ "1" +"</td>\n" +
			"         <td width=\"40%\" >"+ "1" +"</td>\n" +
			"      </tr>\n" +
			"   </thead>\n" +
			"   <tbody>\n" +
			"      <tr>\n" +
			"         <td>{0}</td>\n" +
			"         <td>{1}</td>\n" +
			"         <td>{2}</td>\n" +
			"         <td>"+ "1" +"</td>\n" +
			"         <td>{3}</td>\n" +
			"      </tr>\n" +
			"   </tbody>\n" +
			"</table>";
	public static void main(String[] args) {
		System.out.println(mailBodyTemplate);
		System.out.println(mailBodyTemplate);
	}
	@Autowired
	private JavaMailSender mailSender;

	@Autowired
	RocketMqConfig rocketMqConfig;
	
	/**
	 * threaf module
	 */
	@Autowired
	private TemplateEngine templateEngine;

	@Override
	public void sendMail(String content, String title) throws Exception {
		String to = rocketMqConfig.getTo();
		//按照逗号 分割数据
		List<String> splitByComma = StringUtils.splitByComma(to);
		log.info("splitByComma : [{}]", splitByComma);
		for (String toOne : splitByComma) {
			// 创建message
			MimeMessage message = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setFrom(rocketMqConfig.getFrom());
			// 收件人
			helper.setTo(toOne);
			// 邮件标题
			helper.setSubject(title);
			helper.setText(content, true);
			// 发送邮件
			mailSender.send(message);
		}
		
		

	}



	@Override
	public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
		MessageExt msg = null;
		try {
			for (int i = 0; i < msgs.size(); i++) {
				msg = msgs.get(i);

				log.info("msgs size: [{}]", msgs.size());
				
					String topic = msg.getTopic();
					String tags = msg.getTags();
					String keys = msg.getKeys();
					String msgContent = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET);
					log.info(topic + "  " + tags + "  " + keys + "  " + msgContent + "  ");
					Context contextHtml = new Context();
					HashMap<String, Object> msgMap = JSON.parseObject(msgContent, HashMap.class);
					Iterator<Map.Entry<String, Object>> it = msgMap.entrySet().iterator();
				    while (it.hasNext()) {
				        Map.Entry<String, Object> entry = it.next();
				     // 设置参数
						contextHtml.setVariable(entry.getKey(), entry.getValue());
				    }
				    contextHtml.setVariable("msgContent", msgContent);
					
					// emailTemplate为模板文件的文件名，即html demo的文件名
					String tempContext = templateEngine.process("sendMail", contextHtml);
					sendMail(tempContext, String.valueOf(msgMap.get("msg")));
			
			}


		} catch (Exception e) {
			log.error(e.toString());
			String topic = msg.getTopic();
			String tags = msg.getTags();
			String keys = msg.getKeys();
			log.error(topic + "  " + tags + "  " + keys + "  " + msg.getReconsumeTimes());

			// 第三次就回收
			if (msg.getReconsumeTimes() >= 2) {
				// 加入补偿表中
				log.error("加入补偿表");
				return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
			}
			return ConsumeConcurrentlyStatus.RECONSUME_LATER;
		}
		log.info("执行成功");
		return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;

	}

}
